
import { Disposable, scoped, Lifecycle } from 'tsyringe';
import type { View } from 'ui'
importClass('android.view.WindowManager');
importClass("android.view.Gravity");
importClass("android.graphics.PixelFormat");

declare const WindowManager: any;
import { IFloatyWindow, IFloatyWindowOn } from '../core/floatWindow';
import type { FloatyWindow as IWindow } from 'floaty';
import { Thread } from 'threads';

@scoped(Lifecycle.ContainerScoped)
export class FloatyWindow implements Disposable, IFloatyWindow {
    window: IWindow & {
        [prop: string]: View;
    };
    private emitter = events.emitter()
    on(key: 'ON_CLICK' | string, fn: IFloatyWindowOn) {
        this.emitter.on(key, (...args: any[]) => fn(...args))
    }
    emit(key: string, ...args: any[]) {
        this.emitter.emit(key, ...args)
    }
    private task: Thread;
    public parseWindow: IWindow & {
        [prop: string]: View;
    };
    getParseWindow() {
        if (this.parseWindow) return this.parseWindow
        this.parseWindow = floaty.window(`<vertical visibility="invisible"><input id="input" w="*"h="50"/></vertical>`)
        return this.parseWindow;
    }
    render(xml: string) {
        if (this.window) {
            this.window.close();
        }
        this.window = floaty.window(xml)
        if (this.task && this.task.interrupt) {
            this.task.interrupt()
        }
        this.task = threads.start(() => {
            ui.run(() => {
                const parentParent = this.window.main.parent.parent.parent;
                let params = parentParent.layoutParams || {};
                if (params.flags == 16777736) {
                    log("当前可以触摸, 修改为不可触摸");
                    params.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
                } else if (params.flags == 16777752) {
                    log("当前不可以触摸, 修改为可触摸");
                    params.flags &= ~WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
                }
                const windowManager = context.getSystemService(context.WINDOW_SERVICE);
                windowManager.updateViewLayout(parentParent, params);
                const w = this.window;
                let wh = w.getHeight();
                let dw = device.width;
                let dh = device.height;
                w.setSize(dw + 100, wh);
                w.main.attr('alpha', 1)
                // 悬浮窗置于底部中央
                let y = dh - wh;
                w.setPosition(0, y);
            })
        })
    }
    dispose(): void | Promise<void> {
        if (this.window) this.window.close()
        if (this.parseWindow) this.parseWindow.close()
        this.window = null;
        this.parseWindow = null;
        this.emitter.removeAllListeners()
        if (this.task && this.task.interrupt) {
            this.task.interrupt()
        }
    }
}
